package com.rpc.core.server;

import com.rpc.core.Message;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author wjwei
 * 模拟注册中心
 */
public class LocalRegistry {
    public ConcurrentHashMap<String, BeanMethod> map = new ConcurrentHashMap<>();

    /**
     * 静态单例模式
     */
    public static class Builder {
        private static final LocalRegistry REGISTRY = new LocalRegistry();
    }
    public static LocalRegistry getInstance() {
        return Builder.REGISTRY;
    }

    public Object process(Message message){
        String key=message.getClassName()+"."+message.getMethodName();
        BeanMethod beanMethod=map.get(key);
        if(beanMethod==null){
            return null;
        }
        Object bean=beanMethod.getBean();
        Method method=beanMethod.getMethod();
        try {
            return method.invoke(bean,message.getArgs());
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }
}
